#include "./../inc/struct.h"
#include <math.h>

#define _DBL_MIN 0.001
int ufoRectEqual(const ufoRect *a, const ufoRect *b)
{
	return fabs(a->left - b->left) <= _DBL_MIN && fabs(a->top - b->top) <= _DBL_MIN 
		&& fabs(a->right - b->right) <= _DBL_MIN && fabs(a->bottom - b->bottom) <= _DBL_MIN;
}

int ufoRectIntersection(const ufoRect *in1, const ufoRect *in2, ufoRect *out)
{
    *out = *in1;
    
    if (in2->left > in1->left) {
        out->left = in2->left;
    }
    
    if (in2->top > in1->top) {
        out->top = in2->top;
    }
    
    if (in2->right < in1->right) {
        out->right = in2->right;
    }
    
    if (in2->bottom < in1->bottom) {
        out->bottom = in2->bottom;
    }
    
    if (!ufoRectIsEmpty(out)) {
        return 1;
    }
    
    return 0;
}

int ufoRectMerge(const ufoRect *in1, const ufoRect *in2, ufoRect *out)
{
    if (ufoRectIsEmpty(in1)) {
        *out = *in2;
        return 1;
    }
    
    if (ufoRectIsEmpty(in2)) {
        *out = *in1;
        return 1;
    }
    
    *out = *in1;
    
    if (in2->left < in1->left) {
        out->left = in2->left;
    }
    
    if (in2->top < in1->top) {
        out->top = in2->top;
    }
    
    if (in2->right > in1->right) {
        out->right = in2->right;
    }
    
    if (in2->bottom > in1->bottom) {
        out->bottom = in2->bottom;
    }
    
    return 1;
}

int ufoRectOffset(ufoRect *rc, float x, float y)
{
    rc->left += x;
    rc->right += x;
    rc->top += y;
    rc->bottom += y;
    return 1;
}

int ufoRectMoveTo(ufoRect *rc, float x, float y)
{
	float width = rc->right-rc->left;
	float height = rc->bottom-rc->top;

	rc->left  = x;
	rc->right = x + width;
	rc->top   = y;
	rc->bottom = y + height;
	return 1;
}

int ufoRectIsEmpty(const ufoRect * rect)
{
    return !(rect->right > rect->left && rect->bottom > rect->top);
}

int ufoRectIsPointIn(const ufoRect *rect, float x, float y)
{
    return x >= rect->left && x <= rect->right && y >= rect->top && y <= rect->bottom;
}